class Element {
  constructor(type, props, children) {
    this.type = type;
    this.props = props;
    this.children = children;
  }
}

// 创
const createElement = (type, props, children) => {
  return new Element(type, props, children);
};

// 给真实节点添加属性
function setAttr(node, key, value) {
  switch (key) {
    case 'value':
      if (
        node.tagName.toUpperCase() === 'INPUT' ||
        node.tagName.toUpperCase() === 'TEXTAREA'
      ) {
        node.value = value;
      } else {
        node.setAttribute(key, value);
      }
      break;
    case 'style':
      node.style.cssText = value;
      break;
    default:
      node.setAttribute(key, value);
      break;
  }
}

// render 方法，将虚拟dom转为真是dom
const render = (eleObj) => {
  let type = eleObj.type;
  let props = eleObj.props;
  let el = document.createElement(type);
  for (let key in props) {
    setAttr(el, key, props[key]);
  }
  eleObj.children.forEach((child) => {
    child instanceof Element ? render(child) : document.createTextNode(child);
    el.appendChild(child);
  });
  return el;
};

// 将元素插入页面
const renderDOM = (el, target) => {
  target.appendChild(el);
};

export { render, renderDOM, createElement, Element, setAttr };
